package com.opengroupe.recognize;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

	private String LOG_TAG = "PhotoHandler";
	private final Context context;

	public PhotoHandler(Context context) {
		this.context = context;
	}

	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		File pictureFileDir = getDir();
		if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
			Log.d(LOG_TAG, "Impossible de creer le dossier pour enregistrer l'image.");
			Toast.makeText(context, "Impossible de creer le dossier pour enregistrer l'image.", Toast.LENGTH_LONG).show();
			return;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss", Locale.FRANCE);
		String date =  dateFormat.format(new Date());
		String photoFile = "SCAN_" + date + ".jpg";
		String filename = pictureFileDir.getPath() + File.separator + photoFile;
		Log.i("recognize", "filename: " + filename);
		MainActivity.filename = filename;
		File pictureFile = new File(filename);
		try {
			FileOutputStream fos = new FileOutputStream(pictureFile);
			fos.write(data);
			fos.close();
			Toast.makeText(context, photoFile, Toast.LENGTH_SHORT).show();
		} catch (Exception error) {
			Log.e(LOG_TAG, "Le fichier " + filename + " n'a pas �t� enregistrer: " + error.getMessage());
			Toast.makeText(context, "L'image ne peux pas �tre enregistrer.", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 *  Récupéararion du chemin du répertoire de travail.
	 * @return
	 */
	public static File getDir() {
		File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		return new File(sdDir, "recognize");
	}
}
